package com.jweb.framework.http.interceptors;
import java.security.Principal;
import java.security.cert.X509Certificate;

import javax.servlet.http.HttpServletRequest;

import com.jweb.framework.core.ContextEx;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：
 */
public class DefaultContextProcessor implements ContextProcessor {
	
public static String JAVA_HTTP_X509 = "javax.servlet.request.X509Certificate" ;
	
	protected X509Certificate resolveCertificate(HttpServletRequest httpServletRequest){
		X509Certificate[] x509Certificates = (X509Certificate[]) httpServletRequest.getAttribute(JAVA_HTTP_X509);
		
		if(x509Certificates!=null && x509Certificates.length > 0){
			return x509Certificates[0];
		}
		return null;
	}

	public void postAttributes(ContextEx contextex,HttpServletRequest httpservletrequest) {
		
	}

	public void resolveAttributes(ContextEx contextEx,HttpServletRequest request) {
		
		contextEx.setAttribute("x-source", resovleRemoteAddress(request));
		// Principal 此接口表示主体的抽象概念，它可以用来表示任何实体，例如，个人、公司或登录id
		Principal principal = resolvePrincipal(request);
		if(principal != null){
			contextEx.setAttribute("x-principal", principal);
		}
		String str = resolveToken(request);
		if(str!=null){
			contextEx.setAttribute("x-token", str);
		}
		X509Certificate x509Certificate = resolveCertificate(request);
		if(x509Certificate != null){
			contextEx.setAttribute("x-certification", x509Certificate);
		}
	}

	private String resolveToken(HttpServletRequest request) {
		return null;
	}

	private Principal resolvePrincipal(HttpServletRequest request) {
		return request.getUserPrincipal();
	}

	private Object resovleRemoteAddress(HttpServletRequest request) {
		
		String str = request.getHeader("x-forwarded-for");
		if(str!=null && str.length()>0 && "unknown".equalsIgnoreCase(str)){
			return str ;
		}
		
		str = request.getHeader("Proxy-Client-IP");
		if(str!=null && str.length()>0 && "unknown".equalsIgnoreCase(str)){
			return str ;
		}
		
		str = request.getHeader("WL-Proxy-Client-IP");
		if(str!=null && str.length()>0 && "unknown".equalsIgnoreCase(str)){
			return str ;
		}
		str = request.getRemoteAddr();
		return str;
	}
	
}
